<template>
  <view class="my-rewards-page">
    <!-- 自定义导航栏 -->
    <nav-bar title="我的赏金" :show-back="true"></nav-bar>
    
    <!-- 标签切换 -->
    <view class="tab-switch">
      <view 
        class="tab-item"
        :class="{ active: activeTab === 'publish' }"
        @click="switchTab('publish')"
      >
        我发布的
      </view>
      <view 
        class="tab-item"
        :class="{ active: activeTab === 'accept' }"
        @click="switchTab('accept')"
      >
        我接受的
      </view>
    </view>
    
    <!-- 状态筛选 -->
    <scroll-view class="filter-scroll" scroll-x>
      <view class="filter-list">
        <view 
          v-for="filter in statusFilters"
          :key="filter.value"
          class="filter-item"
          :class="{ active: currentFilter === filter.value }"
          @click="setFilter(filter.value)"
        >
          {{ filter.label }}
        </view>
      </view>
    </scroll-view>
    
    <!-- 任务列表 -->
    <scroll-view 
      class="reward-list"
      scroll-y
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="filteredRewards.length > 0" class="rewards-container">
        <view 
          v-for="reward in filteredRewards" 
          :key="reward.id"
          class="reward-item"
          @click="viewRewardDetail(reward)"
        >
          <view class="reward-header">
            <view class="header-left">
              <view class="reward-type" :class="reward.rewardType">
                {{ reward.rewardType === 'pickup' ? '取件' : '求助' }}
              </view>
              <text class="reward-title">{{ reward.title }}</text>
            </view>
            <view class="reward-amount">¥{{ reward.amount }}</view>
          </view>
          
          <view class="reward-content">
            <text class="reward-desc">{{ reward.content }}</text>
            
            <view class="reward-images" v-if="reward.images && reward.images.length > 0">
              <image 
                v-for="(image, imgIndex) in reward.images.slice(0, 3)"
                :key="imgIndex"
                :src="image"
                mode="aspectFill"
                class="reward-image"
              ></image>
              <view class="image-count" v-if="reward.images.length > 3">+{{ reward.images.length - 3 }}</view>
            </view>
          </view>
          
          <view class="reward-footer">
            <view class="footer-info">
              <view class="info-item">
                <tn-icon name="location" size="24" color="#999999"></tn-icon>
                <text>{{ reward.deliveryAddress || '无地址信息' }}</text>
              </view>
              <view class="info-item">
                <tn-icon name="time" size="24" color="#999999"></tn-icon>
                <text>{{ formatTime(reward.createTime) }}</text>
              </view>
            </view>
            
            <view class="reward-status" :class="reward.rewardStatus">
              {{ getStatusText(reward.rewardStatus) }}
            </view>
          </view>
          
          <!-- 操作按钮区域 -->
          <view class="reward-actions" v-if="activeTab === 'publish'">
            <button 
              class="action-btn primary-btn"
              v-if="reward.rewardStatus === 'published'"
              @click.stop="cancelReward(reward)"
            >
              取消发布
            </button>
            <button 
              class="action-btn primary-btn"
              v-if="reward.rewardStatus === 'accepted'"
              @click.stop="completeReward(reward)"
            >
              确认完成
            </button>
            <button 
              class="action-btn delete-btn"
              v-if="['published', 'completed', 'closed'].includes(reward.rewardStatus)"
              @click.stop="confirmDelete(reward)"
            >
              删除任务
            </button>
          </view>
          
          <view class="reward-actions" v-else-if="activeTab === 'accept'">
            <button 
              class="action-btn primary-btn"
              v-if="reward.rewardStatus === 'accepted'"
              @click.stop="contactPublisher(reward)"
            >
              联系发布者
            </button>
            <button 
              class="action-btn danger-btn"
              v-if="reward.rewardStatus === 'accepted'"
              @click.stop="cancelAccept(reward)"
            >
              取消接单
            </button>
          </view>
        </view>
      </view>
      
      <!-- 无数据状态 -->
      <view v-else class="empty-state">
        <image src="/static/images/empty-reward.png" mode="aspectFit" class="empty-image"></image>
        <text class="empty-text">
          {{ activeTab === 'publish' ? '暂无发布的赏金任务' : '暂无接单记录' }}
        </text>
        <button class="create-btn" v-if="activeTab === 'publish'" @click="createReward">发布赏金任务</button>
        <button class="create-btn" v-else @click="browseRewards">去浏览赏金任务</button>
      </view>
      
      <!-- 加载更多 -->
      <view class="loading-more" v-if="hasMore && filteredRewards.length > 0">
        <tn-loading mode="circle" size="24"></tn-loading>
        <text>加载更多...</text>
      </view>
      
      <view class="no-more" v-if="!hasMore && filteredRewards.length > 0">
        <text>没有更多任务了</text>
      </view>
    </scroll-view>
    
    <!-- 悬浮按钮 -->
    <view class="float-btn" @click="createReward" v-if="activeTab === 'publish'">
      <tn-icon name="add" size="32" color="#FFFFFF"></tn-icon>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import NavBar from '@/components/navbar/NavBar.vue';

// 当前标签和筛选条件
const activeTab = ref('publish');
const currentFilter = ref('all');

// 状态筛选选项
const statusFilters = [
  { label: '全部', value: 'all' },
  { label: '已发布', value: 'published' },
  { label: '已接单', value: 'accepted' },
  { label: '已完成', value: 'completed' },
  { label: '已关闭', value: 'closed' }
];

// 任务数据
const publishedRewards = ref([]);
const acceptedRewards = ref([]);
const isRefreshing = ref(false);
const hasMore = ref(true);

// 切换标签
const switchTab = (tab) => {
  activeTab.value = tab;
  hasMore.value = true;
};

// 设置筛选条件
const setFilter = (filter) => {
  currentFilter.value = filter;
};

// 过滤后的任务列表
const filteredRewards = computed(() => {
  const rewards = activeTab.value === 'publish' ? publishedRewards.value : acceptedRewards.value;
  
  if (currentFilter.value === 'all') {
    return rewards;
  }
  
  return rewards.filter(reward => reward.rewardStatus === currentFilter.value);
});

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'published': '待接单',
    'pending': '审核中',
    'accepted': '进行中',
    'completed': '已完成',
    'closed': '已关闭'
  };
  return statusMap[status] || status;
};

// 时间格式化
const formatTime = (dateString) => {
  const date = new Date(dateString);
  const now = new Date();
  
  // 计算时间差（毫秒）
  const diff = now - date;
  
  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚';
  }
  
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return Math.floor(diff / (60 * 1000)) + '分钟前';
  }
  
  // 小于1天
  if (diff < 24 * 60 * 60 * 1000) {
    return Math.floor(diff / (60 * 60 * 1000)) + '小时前';
  }
  
  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前';
  }
  
  // 大于30天显示具体日期
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 查看任务详情
const viewRewardDetail = (reward) => {
  uni.navigateTo({
    url: `/pages/detail/reward-detail?id=${reward.id}`
  });
};

// 发布新任务
const createReward = () => {
  uni.navigateTo({
    url: '/pages/publish/reward'
  });
};

// 浏览任务列表
const browseRewards = () => {
  uni.switchTab({
    url: '/pages/trade/trade'
  });
};

// 取消发布任务
const cancelReward = (reward) => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消发布此赏金任务吗？',
    success: (res) => {
      if (res.confirm) {
        // 实际项目中应该调用API取消任务
        const index = publishedRewards.value.findIndex(item => item.id === reward.id);
        if (index !== -1) {
          publishedRewards.value[index].rewardStatus = 'closed';
          
          uni.showToast({
            title: '已取消发布',
            icon: 'success'
          });
        }
      }
    }
  });
};

// 确认完成任务
const completeReward = (reward) => {
  uni.showModal({
    title: '确认完成',
    content: '确认任务已完成并支付赏金？',
    success: (res) => {
      if (res.confirm) {
        // 实际项目中应该调用API确认完成
        const index = publishedRewards.value.findIndex(item => item.id === reward.id);
        if (index !== -1) {
          publishedRewards.value[index].rewardStatus = 'completed';
          
          uni.showToast({
            title: '任务已完成',
            icon: 'success'
          });
        }
      }
    }
  });
};

// 确认删除
const confirmDelete = (reward) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个赏金任务吗？删除后无法恢复',
    confirmColor: '#FF5252',
    success: (res) => {
      if (res.confirm) {
        deleteReward(reward);
      }
    }
  });
};

// 删除任务
const deleteReward = (reward) => {
  // 实际项目中应该调用API删除任务
  const index = publishedRewards.value.findIndex(item => item.id === reward.id);
  if (index !== -1) {
    publishedRewards.value.splice(index, 1);
    
    uni.showToast({
      title: '删除成功',
      icon: 'success'
    });
  }
};

// 联系发布者
const contactPublisher = (reward) => {
  // 实际项目中应该跳转到聊天页面
  uni.navigateTo({
    url: `/pages/message/chat?userId=${reward.userId}&userName=${encodeURIComponent('任务发布者')}`
  });
};

// 取消接单
const cancelAccept = (reward) => {
  uni.showModal({
    title: '取消接单',
    content: '确定要取消接单吗？这可能会影响您的信用记录',
    confirmColor: '#FF5252',
    success: (res) => {
      if (res.confirm) {
        // 实际项目中应该调用API取消接单
        const index = acceptedRewards.value.findIndex(item => item.id === reward.id);
        if (index !== -1) {
          acceptedRewards.value.splice(index, 1);
          
          uni.showToast({
            title: '已取消接单',
            icon: 'success'
          });
        }
      }
    }
  });
};

// 加载更多
const loadMore = () => {
  if (!hasMore.value) return;
  
  console.log('加载更多任务');
  
  // 实际项目中应该调用API加载更多任务
  setTimeout(() => {
    const currentRewards = activeTab.value === 'publish' ? publishedRewards : acceptedRewards;
    
    if (currentRewards.value.length >= 20) {
      hasMore.value = false;
      return;
    }
    
    // 模拟新数据
    const count = 5;
    const startId = currentRewards.value.length + 1;
    const newRewards = generateMockRewards(startId, count, activeTab.value);
    
    if (activeTab.value === 'publish') {
      publishedRewards.value = [...publishedRewards.value, ...newRewards];
    } else {
      acceptedRewards.value = [...acceptedRewards.value, ...newRewards];
    }
  }, 1000);
};

// 下拉刷新
const onRefresh = () => {
  isRefreshing.value = true;
  
  // 实际项目中应该调用API刷新任务列表
  console.log('刷新任务列表');
  
  // 模拟刷新完成
  setTimeout(() => {
    isRefreshing.value = false;
    
    // 重置数据
    if (activeTab.value === 'publish') {
      initPublishedRewards();
    } else {
      initAcceptedRewards();
    }
  }, 1000);
};

// 生成模拟发布的任务数据
const generateMockRewards = (startId, count, type) => {
  const result = [];
  const rewardTypes = ['pickup', 'help'];
  const statuses = ['published', 'accepted', 'completed', 'closed'];
  
  for (let i = 0; i < count; i++) {
    const id = startId + i;
    const rewardType = rewardTypes[Math.floor(Math.random() * rewardTypes.length)];
    const imageCount = Math.floor(Math.random() * 4); // 0-3张图片
    const images = [];
    
    for (let j = 0; j < imageCount; j++) {
      const imgId = 200 + Math.floor(Math.random() * 100);
      images.push(`https://picsum.photos/id/${imgId}/200/200`);
    }
    
    // 选择状态，根据类型不同有不同概率
    let statusPool = [...statuses];
    if (type === 'accept') {
      // 接单的任务更可能是"已接单"或"已完成"状态
      statusPool = ['accepted', 'accepted', 'completed'];
    }
    
    const randomStatus = statusPool[Math.floor(Math.random() * statusPool.length)];
    
    result.push({
      id,
      userId: 1000 + Math.floor(Math.random() * 100),
      title: rewardType === 'pickup' ? 
        `帮忙取${['快递', '外卖', '文件', '包裹', '蛋糕'][i % 5]} ${id}` : 
        `求助：${['搬东西', '找资料', '借工具', '问路', '借充电宝'][i % 5]} ${id}`,
      content: `这是一条${rewardType === 'pickup' ? '取件' : '求助'}任务的详细描述，说明了任务的具体要求和注意事项。这是任务 ${id} 的描述。`,
      images,
      amount: 5 + Math.floor(Math.random() * 30), // 5-35元赏金
      scope: 'current',
      deliveryAddress: rewardType === 'pickup' ? `校区${Math.floor(Math.random() * 3) + 1}号宿舍楼${Math.floor(Math.random() * 10) + 1}层` : null,
      contactName: `用户${1000 + id}`,
      contactPhone: `1388888${(1000 + id).toString().padStart(4, '0')}`,
      rewardType,
      rewardStatus: randomStatus,
      createTime: new Date(new Date().getTime() - id * 3600000 * (Math.random() * 24))
    });
  }
  
  return result;
};

// 初始化发布的任务列表
const initPublishedRewards = () => {
  publishedRewards.value = generateMockRewards(1, 10, 'publish');
  hasMore.value = true;
};

// 初始化接受的任务列表
const initAcceptedRewards = () => {
  acceptedRewards.value = generateMockRewards(1, 10, 'accept');
  hasMore.value = true;
};

onMounted(() => {
  // 初始化任务列表
  initPublishedRewards();
  initAcceptedRewards();
});
</script>

<style lang="scss" scoped>
.my-rewards-page {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 100rpx;
}

.tab-switch {
  display: flex;
  background-color: #ffffff;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  .tab-item {
    flex: 1;
    height: 60rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 30rpx;
    color: #666666;
    position: relative;
    
    &.active {
      color: #32C5FF;
      font-weight: bold;
      
      &::after {
        content: '';
        position: absolute;
        bottom: -10rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 6rpx;
        background-color: #32C5FF;
        border-radius: 4rpx;
      }
    }
  }
}

.filter-scroll {
  background-color: #ffffff;
  height: 80rpx;
  white-space: nowrap;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  
  .filter-list {
    display: inline-flex;
    padding: 0 20rpx;
    height: 100%;
    align-items: center;
  }
  
  .filter-item {
    padding: 0 24rpx;
    height: 56rpx;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    font-size: 26rpx;
    color: #666666;
    margin-right: 20rpx;
    background-color: #f5f5f5;
    border-radius: 28rpx;
    
    &.active {
      background-color: rgba(50, 197, 255, 0.1);
      color: #32C5FF;
      font-weight: bold;
    }
    
    &:last-child {
      margin-right: 0;
    }
  }
}

.reward-list {
  flex: 1;
  padding: 20rpx;
}

.rewards-container {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.reward-item {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  
  .reward-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16rpx;
    
    .header-left {
      display: flex;
      align-items: center;
      flex: 1;
    }
    
    .reward-type {
      padding: 4rpx 12rpx;
      border-radius: 20rpx;
      font-size: 24rpx;
      margin-right: 16rpx;
      
      &.pickup {
        background-color: rgba(50, 197, 255, 0.1);
        color: #32C5FF;
      }
      
      &.help {
        background-color: rgba(186, 104, 200, 0.1);
        color: #BA68C8;
      }
    }
    
    .reward-title {
      font-size: 30rpx;
      font-weight: bold;
      color: #333333;
      flex: 1;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    
    .reward-amount {
      font-size: 34rpx;
      font-weight: bold;
      color: #FF5252;
    }
  }
  
  .reward-content {
    margin-bottom: 16rpx;
    
    .reward-desc {
      font-size: 26rpx;
      color: #666666;
      line-height: 1.5;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      margin-bottom: 16rpx;
    }
    
    .reward-images {
      display: flex;
      gap: 10rpx;
      position: relative;
      
      .reward-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 8rpx;
      }
      
      .image-count {
        position: absolute;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        color: #ffffff;
        font-size: 24rpx;
        width: 50rpx;
        height: 50rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border-top-left-radius: 8rpx;
      }
    }
  }
  
  .reward-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 16rpx;
    border-top: 1px solid #f5f5f5;
    
    .footer-info {
      flex: 1;
      
      .info-item {
        display: flex;
        align-items: center;
        margin-bottom: 8rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        text {
          font-size: 24rpx;
          color: #999999;
          margin-left: 6rpx;
        }
      }
    }
    
    .reward-status {
      padding: 4rpx 12rpx;
      border-radius: 20rpx;
      font-size: 24rpx;
      
      &.published {
        background-color: rgba(33, 150, 243, 0.1);
        color: #2196F3;
      }
      
      &.accepted {
        background-color: rgba(255, 152, 0, 0.1);
        color: #FF9800;
      }
      
      &.completed {
        background-color: rgba(76, 175, 80, 0.1);
        color: #4CAF50;
      }
      
      &.closed {
        background-color: rgba(158, 158, 158, 0.1);
        color: #9E9E9E;
      }
    }
  }
  
  .reward-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 20rpx;
    gap: 20rpx;
    
    .action-btn {
      min-width: 160rpx;
      height: 60rpx;
      border-radius: 30rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 26rpx;
      padding: 0 30rpx;
      
      &::after {
        border: none;
      }
    }
    
    .primary-btn {
      background: linear-gradient(135deg, #32C5FF, #2196F3);
      color: #ffffff;
    }
    
    .delete-btn {
      background-color: #f5f5f5;
      color: #FF5252;
    }
    
    .danger-btn {
      background-color: #f5f5f5;
      color: #FF5252;
      border: 1px solid #FF5252;
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
  
  .empty-image {
    width: 250rpx;
    height: 250rpx;
    margin-bottom: 30rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999999;
    margin-bottom: 40rpx;
  }
  
  .create-btn {
    width: 300rpx;
    height: 80rpx;
    background: linear-gradient(135deg, #32C5FF, #BA68C8);
    color: #ffffff;
    border-radius: 40rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 28rpx;
    
    &::after {
      border: none;
    }
  }
}

.loading-more, .no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 0;
  font-size: 24rpx;
  color: #999999;
  
  text {
    margin-left: 10rpx;
  }
}

.float-btn {
  position: fixed;
  right: 30rpx;
  bottom: 100rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #32C5FF, #BA68C8);
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.2);
  z-index: 10;
}
</style> 